var express = require('express');
var router = express.Router();
const { query } = require('../db');
const app = express()
//通过json这个中间件解析json格式的数据
app.use(express.json())
//通过使用urlencoded解码数据
app.use(express.urlencoded({ extended: false }));


// 入住
router.post('/ruzhu', async function (req, res, next) {
    // 获取参数 

    var paymentPassword = req.body.paymentPassword;
    var account = req.body.account;
    var user_name = req.body.user_name;
    // 支付金额

    var room_id = req.body.id;
    var roomnum = req.body.roomnum;
    var date_s = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
    var income = Number(req.body.income);
    // 未入账
    var state = 0;

     // 只可以预约一间房
     var check_sql = `select * from hotel_room where user_accout='${account}' `;
     var check_result = await query(check_sql).catch(next);
     if (check_result.length >= 1) {
         res.json({
             code: -9999,
             msg: "只可以预约一间房"
         })
         return false
     }
     
 
    

    // 将余额减少
    var sql_balance = `select * from user where account='${account}' and  paymentPassword='${paymentPassword}' `;
    var res_balance = await query(sql_balance).catch(next);
// console.log(res_balance)
   if(res_balance.length==0){
    
    res.json({
        code: -9999,
        msg: "密码错误"
    })
    return false
   }

  
        // console.log(res_balance.length[0].balance,"res_balance.length[0].balance")
    if (res_balance[0].balance >= income) {
        var jiansho_sql = `update user set balance=balance-${income} where account='${account}' and  paymentPassword='${paymentPassword}'`;
      
        var jianshao_res = await query(jiansho_sql).catch(next);

        //   加入到收入表
        var income_sql = `INSERT INTO income(room_id,roomnum,date_s,income,account,state) VALUES('${room_id}','${roomnum}',
        '${date_s}','${income}','${account}','${state}')`;
        var income_res = await query(income_sql).catch(next);

         // 先将房间改为已经预约 
     var hotel_room_sql = `UPDATE hotel_room SET roomstate=1,user_accout='${account}',user_name='${user_name}' 
      WHERE id=${room_id}`;
      console.log(hotel_room_sql,"--")
     var hotel_room_result = await query(hotel_room_sql).catch(next);

        if (hotel_room_result) {
            res.json({
                code: 200,
                msg: "支付成功!"
            })
        } else {
            res.json({
                code: -9999,
                msg: "系统错误"
            })
        }

    }

    else {
        res.json({
            code: -9999,
            msg: "余额不足"
        })
    }



   
   

   
})

// 时间格式函数
function dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}
//获取列表
router.post('/list', async function (req, res, next) {
    // 获取分页参数
    var key = req.body.key || '';
    var pageNum = Number(req.body.pageNum);
    var pageSize = Number(req.body.pageSize);
    var start = (pageNum - 1) * pageSize;
    var user_type = req.body.user_type;
    var account = req.body.account;

    var sql = "";

    if (user_type == 1) {
        sql = `select * from work_log  where account='${account}'  ORDER BY id desc   limit ${start},${pageSize} `;
    }
    else {
        sql = `select * from work_log   ORDER BY id desc   limit ${start},${pageSize} `;
    }
    // 查询数据库
    var result = await query(sql).catch(next)
    var sql_all = 'select * from  work_log ';
    var result_all = await query(sql_all).catch(next);
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            data: result,
            total: result_all.length
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})
// 添加
router.post('/add', async function (req, res, next) {
    // 获取参数 号 状态 价格

    var works = req.body.works;
    var account = req.body.account;
    var supername = req.body.supername;
    var dates_ = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
    // 
    var sql = `INSERT INTO work_log(works,account,supername,dates_) VALUES('${works}','${account}','${supername}','${dates_}')`;
    var result = await query(sql).catch(next);

    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "添加成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})

// 删除
router.post('/del', async function (req, res, next) {
    // 获取参数
    var id = Number(req.body.id);
    var sql = `delete from work_log where id=${id} `
    // 查询数据库
    var result = await query(sql).catch(next)
    // 返回数据
    if (result) {
        res.json({
            code: 200,
            msg: "成功!"
        })
    } else {
        res.json({
            code: -9999,
            msg: "系统错误"
        })
    }
})




module.exports = router;

